package com.dj.Demo.反转链表;

//链表节点类
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

class Solution {

    public ListNode ReverseList(ListNode head) {

        ListNode next = null;
        ListNode pre = null;

        while (head != null) {
            // 保存要反转到头的那个节点  [1,] [2,3] [3,1]
            next = head.next; //  next = 2
            // 要反转的那个节点指向已经反转的上一个节点(备注:第一次反转的时候会指向null)
            head.next = pre;  //head.next = null
            // 上一个已经反转到头部的节点
            pre = head; // pre = head = 1
            // 一直向链表尾走
            head = next; // head 2
        }
        return pre;
    }

    public static void main(String[] args) {

        ListNode a = new ListNode(1);
        ListNode b = new ListNode(2);
        ListNode c = new ListNode(3);
        ListNode d = new ListNode(4);
        ListNode e = new ListNode(5);
        a.next = b;
        b.next = c;
        c.next = d;
        d.next = e;
        new Solution().ReverseList(a);
        while (e != null) {
            System.out.println(e.val);
            e = e.next;
        }
    }
}
